// let span_user = document.getElementById("span_user");
// let ss_account = sessionStorage.getItem("account");
// span_user.innerText = ss_account;

let role = [
	{id: 1, name: '张三', sex: '男', telephone: '12345678906', houNum: '1栋',user: '张三'},
	{id: 2, name: '王五', sex: '女', telephone: '12345678907', houNum: '2栋',user: '王五'},
	{id: 3, name: '赵六', sex: '男', telephone: '12345678908', houNum: '3栋',user: '王五'},
	{id: 4, name: '小明', sex: '男', telephone: '12345678904', houNum: '1栋',user: '小明'},
];

let data = localStorage.getItem("data");
if(data) {
	role = JSON.parse(data);
}else {
	localStorage.setItem("data", JSON.stringify(role));
}

let table = document.getElementsByTagName("table")[0];
let tbody = table.getElementsByTagName("tbody")[0];
let $tbody = $("table").find("tbody");

let opt_name = document.getElementById("opt_name");
let opt_telephone = document.getElementById("opt_telephone");
let opt_user = document.getElementById("opt_user");

/**
 * init初始化函数
 */
function init() {
	//绑定事件
	// $("#btn_search").click(search);
	// $("#btn_add").click(toAdd);
	$("#btn_delSelected").click(delSelected);
	$("input[name='cb_select_all']").change(selectAll);
	$tbody.find("tr").dblclick(rowEdit);//双击事件
	// $("#btn_rowEdit").click(save);
	// $("#btn_download").click(download);
}


//清除
function clear() {
	do{
		tbody.removeChild(tbody.firstChild);
	}while(tbody.hasChildNodes());
}

update();

function update(args) {
	for(let index in role) {
		let item = role[index];
		//搜索功能
		if(args) {
			if(args.name.trim().length !== 0 && item.name !== args.name) {
				continue;
			}
			if(args.telephone.trim().length !== 0 && item.telephone !== args.telephone) {
				continue;
			}
			if(args.user.trim().length !== 0 && item.user !== args.user) {
				continue;
			}
		}
		let tr = document.createElement("tr");
		tbody.appendChild(tr);
		
		let ipt = `
			<input type="checkbox" name="cb_select" value="${item.id}" />
		`;
		appendTd(tr, ipt, true);
		
		for(let val in item) {
			let text = item[val];
			let isHtml = false;
			if (val === "name") {
				text = `
					<a href='#' onclick='edit(${index})'>${text}</a>
				`;
				isHtml = true;
			}else if(val === 'count') {
				text = `
					<button type="button" onclick="jian(${index})">-</button>
					<span>${text}</span>
					<button type="button" onclick="jia(${index})">+</button>
				`;
				isHtml = true;
			}
			appendTd(tr, text, isHtml);
		}
		let opt = `
			<button type="button" data-toggle="modal" data-target="#modal_add" style="border-radius: 6px; color:#fff;background-color: #0088cc;border: 1px solid #0088cc;">修改</button>
			<button onclick="del(${index})" style="border-radius: 6px;color:#fff;background-color: red;border: 1px solid red;">删除</button>
		`;
		appendTd(tr, opt, true);
	}
}

function appendTd(tr, value, isHtml) {
	let td = document.createElement("td"); 
	if(isHtml) {
		td.innerHTML = value;
	}else {
		td.innerText = value;
	}
	tr.appendChild(td);
}

//删除
function del(index) {
	let result = confirm("确认是否删除" + role[index].user + "管理员？");
	console.log(result);
	if(!result) {
		return;
	}
	//删除数组中的数据
	role.splice(index, 1);
	clear();
	update();
	//更新localStorage
	localStorage.setItem("data", JSON.stringify(role));
}

//checkbox 全选/取消全选 
var isCheckAll = false; 
function swapCheck() { 
	if (isCheckAll) { 
		$("input[type='checkbox']").each(function() { 
			this.checked = false; 
		}); 
		isCheckAll = false; 
	} else { 
		$("input[type='checkbox']").each(function() { 
			this.checked = true; 
		}); 
		isCheckAll = true; 
	} 
} 

function selectAll() {
	$("input[name='cb_select']").prop("checked", $(this).prop("checked"));
}

function delSelected() {
	//获取所有选中name为cb_select的checkbox
	$("input[name='cb_select']:checked").each(function(index, item) {
		// data.splice($(item).val(), 1);
		for(let i in data) {
			let dataItem = data[i];
			if(parseInt($(item).val()) === dataItem.id) {
				data.splice(i, 1)
			}
		}
	});
	$tbody.empty();
	update();
	saveData2Storage();
}


// 添加
function add() {
	location.href = "add.html";
	sessionStorage.setItem("item", null);
}

//编辑
function edit(index) {
	let item = role[index];
	sessionStorage.setItem("index", index);
	sessionStorage.setItem("item", JSON.stringify(item));
	location.href = "add.html";
}

let input_name = document.getElementsByName("name")[0];
let input_sex = document.getElementsByName("sex")[0];
let input_telephone = document.getElementsByName("telephone")[0];
let input_houNum = document.getElementsByName("houNum")[0];
let input_user = document.getElementsByName("user")[0];
//判断是添加还是编辑
let editItem = JSON.parse(sessionStorage.getItem("item"));
console.log(editItem);
if(editItem) {
	input_name.value = editItem.name;
	input_sex.value = editItem.sex;
	input_telephone.value = editItem.telephone;
	input_houNum.value = editItem.houNum;
	input_user.value = editItem.user;
}
function save(){
	console.log("save");
	let name = input_name.value;
	let sex = input_sex.value;
	let telephone = input_telephone.value;
	let houNum = input_houNum.value;
	let user = input_user.value;
	let obj = {
		id: 1,
		name: name,
		sex:sex,
		telephone: telephone,
		houNum: houNum,
		user: user
	}
	
	//获取数组
	let data = localStorage.getItem("data");
	if(data) {
		data = JSON.parse(data);
		//判断书名是否重复
		for(let index in data) {
			let item = data[index];
			if(editItem) {
				//编辑
				if(editItem.name !== name && item.name === name) {
					alert("用户名不能重复");
					return;
				}
			}else{
				//添加
				if(item.name === name) {
					alert("用户名不能重复");
					return;
				}
			}
			
		}
		if(editItem) {
			let index = sessionStorage.getItem("index");
			data.splice(index, 1, obj)
		}else {
			data.push(obj);//添加
		}
		
		//放回去
		localStorage.setItem("data", JSON.stringify(data));
		//页面跳转
		location.href = 'MainHouParen.html'
	}
}


//搜索
function search() {
	let name = opt_name.value;//获取书名
	let telephone = opt_telephone.value;//获取书名
	let user = opt_user.value;//获取书名
	if(name.trim().length === 0 && telephone.trim().length === 0 && user.trim().length === 0 ) {
		alert("请输入查询条件")
		return;
	}
	clear();
	update({name, telephone, user});
}

$(function() {
	$("#mytable").DataTable({
		"searching": false, //是否启用搜索
		"iDisplayLength": 10,//单页显示的数据的条数
		
		"searching": false, //是否启用搜索
		"sPaginationType": "full_numbers",// 分页，一共两种样式,一种full_numbers 另一种为two_button // 是datatables默认
		"bPaginate": true, //翻页功能 分页按钮
		"bLengthChange": false,//是否允许终端用户从一个选择列表中选择分页的页数，页数为10，25，50和100，需要分页组件bPaginate的支持
		"bFilter": false,//是否对数据进行过滤，搜索栏
		"bSort": false,//是否开启列排序
		"iDisplayLength": 10,//单页显示的数据的条数

		
		"oLanguage": {
		"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
		"sInfoEmpty": "没有数据",
		"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
		"oPaginate": {
			"sFirst": "首页",
			"sPrevious": "上一页",
			"sNext": "下一页",
			"sLast": "尾页"
		},
		"sZeroRecords": "没有检索到数据",
		"sProcessing": "<img src='./loading.gif' />",
		"sSearch": "搜索"
		},
	})
})
